# 获取摄像头以及推流参数
import json

import cv2
import pyzed.sl as sl

from GlobalValues import globalVal, CameraVal


def readConfig():
    f = open('pushConfig.txt', 'r', encoding='utf-8')
    data = json.load(f)

    rtmpUrl = data['rtmp|推流地址']
    sizeStr = data['resolution|分辨率']
    fps = int(data['frameRate|频率'])
    frame_width = int(sizeStr.split('*')[0])
    frame_height = int(sizeStr.split('*')[1])
    # 用于推流的配置,参数比较多，可网上查询理解
    globalVal.command = ['ffmpeg',
                         '-y',
                         '-f', 'rawvideo',
                         '-vcodec', 'rawvideo',
                         '-pix_fmt', 'bgr24',
                         '-s', "{}x{}".format(frame_width, frame_height),  # 图片分辨率
                         '-r', str(fps),  # 视频帧率
                         '-i', '-',
                         '-c:v', 'libx264',
                         '-pix_fmt', 'yuv420p',
                         '-preset', 'ultrafast',
                         '-f', 'flv',
                         rtmpUrl]

    globalVal.vid = cv2.VideoCapture(0)
    globalVal.vid.set(cv2.CAP_PROP_FOURCC, cv2.VideoWriter.fourcc('M', 'J', 'P', 'G'))
    globalVal.vid.set(cv2.CAP_PROP_FRAME_WIDTH, 1280)
    globalVal.vid.set(cv2.CAP_PROP_FRAME_HEIGHT, 720)
    globalVal.vid.set(cv2.CAP_PROP_FPS, fps)

    CameraVal.zed = sl.Camera()
    # Set configuration parameters
    CameraVal.init_params = sl.InitParameters()
    CameraVal.init_params.camera_resolution = sl.RESOLUTION.HD720  # Use HD720 video mode
    CameraVal.init_params.camera_fps = 30  # Set fps at 60
    # init_params.enable_image_enhancement = True

    CameraVal.init_params.depth_mode = sl.DEPTH_MODE.PERFORMANCE  # Use PERFORMANCE depth mode
    CameraVal.init_params.coordinate_units = sl.UNIT.METER  # Use meter units (for depth measurements)

    # Open the camera
    err = CameraVal.zed.open(CameraVal.init_params)
    if err != sl.ERROR_CODE.SUCCESS:
        print(repr(err))
        # exit(-1)

    CameraVal.runtime_parameters = sl.RuntimeParameters()
    CameraVal.runtime_parameters.sensing_mode = sl.SENSING_MODE.STANDARD
    # Setting the depth confidence parameters
    CameraVal.runtime_parameters.confidence_threshold = 100
    CameraVal.runtime_parameters.textureness_confidence_threshold = 100

    CameraVal.image_left = sl.Mat()
    CameraVal.image_right = sl.Mat()
    CameraVal.point_cloud = sl.Mat()

    CameraVal.mirror_ref = sl.Transform()
    CameraVal.mirror_ref.set_translation(sl.Translation(2.75, 4.0, 0))
    CameraVal.tr_np = CameraVal.mirror_ref.m
